<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\AdminBaseController;
use Illuminate\Http\Request;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

/**
 * 角色控制器
 * Class RoleController
 * @package App\Http\Controllers\Admin
 */
class RoleController extends AdminBaseController
{
    // 无需登录的方法
    protected $noNeedLogin = [];

    // 无需鉴权的方法
    protected $noNeedRight = [];
    /**
     * 查询角色列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
        $filter = $request->all();
        $role = new Role();
        $where = [];
        if (isset($filter['title']) && !is_null($filter['title'])) {
            $where[] = ['title', 'like', '%'. $filter['title'] . '%'];
        }
        if (isset($filter['name']) && !is_null($filter['name'])) {
            $where[] = ['name', 'like', '%'. $filter['name'] . '%'];
        }
        $list = $role->where($where)->with('permissions')->get();
        return $this->success($list);
    }

    /**
     * 新增角色
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(Request $request)
    {
        $param = $request->all();
        $role = Role::create($param);
        if (isset($param['permissions'])) {
            $role->givePermissionTo($param['permissions']);
        }
        return $this->success($role);
    }

    /**
     * 更新角色
     * @param Request $request
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(Request $request, $id)
    {
        $param = $request->all();
        $role = Role::findOrFail($id);
        $role->fill($param)->save();
        // 根据传入的权限id更新
        if (isset($param['permissions'])) {
            // 先删除该角色所有权限
            $p_all = Permission::all()->pluck('id');
            $role->revokePermissionTo($p_all);
            $role->givePermissionTo($param['permissions']);
        }
        return $this->success($role, '修改角色信息成功');
    }

    /**
     * 删除角色
     */
    public function destroy($id)
    {
        $role = Role::findOrFail($id);
        $role->delete();
        return $this->success();
    }
}
